package com.kichina.parking.module.message.socket.message;

import com.alibaba.fastjson.JSONObject;
import com.kichina.parking.exception.extend.JsonParseException;
import com.kichina.parking.module.message.socket.IMessageHandler;
import com.kichina.parking.module.message.socket.SocketStorageDeal;
import com.kichina.parking.module.message.socket.bean.BaseSocketResponse;
import com.kichina.parking.module.message.socket.enums.MessageTypeEnum;
import com.kichina.parking.module.message.socket.exception.MessageDealException;
import com.kichina.parking.upstream.Parking10MonthPayRuleUpstreamHandler;
import io.vertx.core.net.NetSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Surging
 * @version 1.0
 * @ClassName SocketMessageCardTypeHandler
 * @date 2022-09-16 14:54
 * @desc 手动开闸后主动上传开闸记录到服务端；
 */
@Component
@Order(Byte.MIN_VALUE + 11)
@Slf4j
public class MonthPayRuleTypeHandler implements IMessageHandler {

    private final Parking10MonthPayRuleUpstreamHandler parking10MonthPayRuleUpstreamHandler;

    public MonthPayRuleTypeHandler(Parking10MonthPayRuleUpstreamHandler parking10MonthPayRuleUpstreamHandler) {
        this.parking10MonthPayRuleUpstreamHandler = parking10MonthPayRuleUpstreamHandler;
    }

    @Override
    public void handler(JSONObject jsonObject, NetSocket netSocket) throws MessageDealException {
        // 保存固定车收费规则信息
        try {
            parking10MonthPayRuleUpstreamHandler.recordParkingMonthPayRuleUpstream(jsonObject);
        } catch (JsonParseException e) {
            if (Objects.nonNull(netSocket)) {
                SocketStorageDeal.sendResponse(netSocket, BaseSocketResponse.buildFailedRuleId(jsonObject.getString("service"), jsonObject.getString("rule_id")));
            }else {
                throw new MessageDealException("固定车收费规则处理发生异常");
            }
        }
        if (Objects.nonNull(netSocket)) {
            SocketStorageDeal.sendResponse(netSocket, BaseSocketResponse.buildSuccessRuleId(jsonObject.getString("service"), jsonObject.getString("rule_id")));
        }
    }

    @Override
    public boolean check(JSONObject jsonObject) {
        return MessageTypeEnum.MONTH_PAY_RULE.getValue().equals(jsonObject.getString("service"));
    }

    @Override
    public boolean interrupt() {
        return true;
    }
}
